package cn.com.thingo.shyintelligent.ui.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.videogo.exception.BaseException;
import com.videogo.exception.ExtraException;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.videogo.util.ConnectionDetector;
import com.videogo.util.LocalValidate;

import com.videogo.util.Base64;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;


import butterknife.BindView;
import cn.bertsir.zbar.QrConfig;
import cn.bertsir.zbar.QrManager;
import cn.com.thingo.shyintelligent.R;
import cn.com.thingo.shyintelligent.app.Constants;
import cn.com.thingo.shyintelligent.base.RootFragment;
import cn.com.thingo.shyintelligent.base.contract.MonitorContract;
import cn.com.thingo.shyintelligent.model.bean.CommonBean;
import cn.com.thingo.shyintelligent.presenter.MonitorPresenter;
import cn.com.thingo.shyintelligent.ui.activity.EzCameraActivity;
import cn.com.thingo.shyintelligent.ui.activity.EzWifiNetConfigActivity;
import cn.com.thingo.shyintelligent.ui.activity.SearchEzDeviceActivity;
import cn.com.thingo.shyintelligent.ui.adapter.MonitorAdapter;
import cn.com.thingo.shyintelligent.ui.adapter.adapterentity.AddItemEntity;
import cn.com.thingo.shyintelligent.ui.adapter.adapterentity.DeviceItemEntity;
import cn.com.thingo.shyintelligent.util.SystemUtil;
import cn.com.thingo.shyintelligent.util.SPUtils;
import cn.com.thingo.shyintelligent.util.ToastUtil;

public class MonitorFragment extends RootFragment<MonitorPresenter> implements MonitorContract.View {
    @BindView(R.id.rv_monitor)
    RecyclerView mRecyclerView;
    private String deviceType = "";
    private BroadcastReceiver mBroadcastReceiver;
    private MonitorAdapter mMonitorAdapter;
    /**
     * 序列号结果变量
     */
    private String mSerialNoStr = null;
    private String mSerialVeryCodeStr = null;
    String[] rooms = {"客厅监控", "走廊监控", "书房监控", "厨房监控"};
    /**
     * 本地数据合法性检测变量
     */
    private LocalValidate mLocalValidate = null;

    public MonitorFragment() {
        // Required empty public constructor
    }

    public static MonitorFragment newInstance() {
        return new MonitorFragment();
    }

    @Override
    protected void initEventAndData() {
        super.initEventAndData();
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                assert action != null;
                switch (action) {
                    case Constants.ACTION_ADD_DEVICE:
                        mPresenter.getDeviceInfoList();
                        break;
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_ADD_DEVICE);
        mContext.registerReceiver(mBroadcastReceiver,intentFilter);
        List<MultiItemEntity> entityList = new ArrayList<>();
        entityList.add(new AddItemEntity());
        mMonitorAdapter = new MonitorAdapter(entityList);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext, 2);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mRecyclerView.setAdapter(mMonitorAdapter);
        mRecyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int position = parent.getChildAdapterPosition(view);
                outRect.bottom = SystemUtil.dp2px(20);
                if (position % 2 == 0) {
                    outRect.right = SystemUtil.dp2px(10);
                    outRect.left = SystemUtil.dp2px(20);
                } else {
                    outRect.left = SystemUtil.dp2px(10);
                    outRect.right = SystemUtil.dp2px(20);
                }
            }
        });

        mMonitorAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                int viewType = adapter.getItemViewType(position);
                switch (viewType) {
                    case MonitorAdapter.ITEM_ROOM:
                        Bundle bundle = new Bundle();
                        bundle.putParcelable(Constants.TAG_ROOM, ((DeviceItemEntity)adapter.getItem(position)).getEZDeviceInfo());
                        Intent intent = new Intent(mContext, EzCameraActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    case MonitorAdapter.ITEM_ADD:
                        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                            ActivityCompat.requestPermissions((Activity) mContext, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2);
                        } else {
                            showAddDeviceDialog();
                        }
                        break;

                }

            }
        });
        mPresenter.getDeviceInfoList();
    }

    private void showAddDeviceDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        final String[] itemAlert = {getString(R.string.ez_pop_scan), getString(R.string.ez_pop_write)};
        builder.setTitle(R.string.select_add_way).setItems(itemAlert, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        showScan();
                        break;
                    case 1:
                        Bundle bundle = new Bundle();
                        bundle.putInt("type", 0);
                        Intent intent = new Intent(mContext, SearchEzDeviceActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        }).setNegativeButton(android.R.string.cancel, null).show();
//                    EzBottomPopwindow ezBottomPopwindow = new EzBottomPopwindow(mContext);
//                    ezBottomPopwindow.setOnEzBottomPopClickListener(new OnEzBottomPopClickListener() {
//                        @Override
//                        public void OnEzAddScanClick(View view) {
//                            showScan();
//                        }
//
//                        @Override
//                        public void OnEzAddWriteClick(View view) {
//                            Bundle bundle = new Bundle();
//                            bundle.putInt("type", 0);
//                            Intent intent = new Intent(mContext, SearchEzDeviceActivity.class);
//                            intent.putExtras(bundle);
//                            startActivity(intent);
//                        }
//                    });
//                    ezBottomPopwindow.showAtLocation(mMonitorView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showAddDeviceDialog();
                } else {
                    ToastUtil.show("请在设置中添加位置权限");
                }
                break;
        }
    }

    private void showScan() {
        QrConfig qrConfig = new QrConfig.Builder()
                .setShowDes(false)
                .setShowLight(true)
                .setShowTitle(true)
                .setShowAlbum(true)
                .setCornerColor(Color.WHITE)
                .setLineColor(Color.WHITE)
                .setLineSpeed(QrConfig.LINE_MEDIUM)
                .setScanType(QrConfig.TYPE_QRCODE)
                .setScanViewType(QrConfig.SCANVIEW_TYPE_QRCODE)
                .setPlaySound(true)
                .setNeedCrop(true)
                .setIsOnlyCenter(true)
                .setShowTitle(false)
                .create();
        QrManager.getInstance().init(qrConfig).startScan(getActivity(), new QrManager.OnScanResultCallback() {
            @Override
            public void onScanSuccess(String resultString) {
                // 关注二维码名片地址
                // 例如：https://test.shipin7.com/h5/qrcode/intro?
                if (resultString.startsWith("https://") && resultString.contains("h5/qrcode/intro")) {
//            HikStat.onEvent(CaptureActivity.this, HikAction.ACTION_QRCODE_focus);
/*            Intent intent = new Intent(this, FollowActivity.class);
            intent.putExtra(IntentConsts.EXTRA_URL, resultString);
            startActivityForResult(intent, REQUEST_CODE_CLOUD);
*/
                    // 设备二维码名片
                } else if (resultString.startsWith("http://") && resultString.contains("smart.jd.com")) {
                    mSerialNoStr = "";
                    mSerialVeryCodeStr = "";
                    deviceType = "";
                    try {
                        String deviceInfoMarker = "$$$";
                        String contentMarker = "f=";
                        resultString = URLDecoder.decode(resultString, "UTF-8");
                        // 验证url有效性 f=打头的为 需要的内容
                        int contentIndex = resultString.indexOf(contentMarker);
                        if (contentIndex < 0) {
                            mSerialNoStr = resultString;
                            isValidate();
                            return;
                        }
                        contentIndex += contentMarker.length();
                        resultString = new String(Base64.decode(resultString.substring(contentIndex).trim()));
                        int index = resultString.indexOf(deviceInfoMarker);
                        // 二次判断有效性 $$$打头的为萤石信息
                        if (index < 0) {
                            mSerialNoStr = resultString;
                            isValidate();
                            return;
                        }
                        index += deviceInfoMarker.length();
                        resultString = resultString.substring(index);
                        String[] infos = resultString.split("\r\n");
                        if (infos.length >= 2) {
                            mSerialNoStr = infos[1];
                        }
                        if (infos.length >= 3) {
                            mSerialVeryCodeStr = infos[2];
                        }
                        if (infos.length >= 4) {
                            deviceType = infos[3];
                        }
                        isValidate();
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                } else {
                    // TODO 判断是否为探测器 1.5个字段 2.最后一个字段T或者K打头 且长度为4
                    if (goAddProbe(resultString)) {
                        return;
                    }
                    // 初始化数据
                    mSerialNoStr = "";
                    mSerialVeryCodeStr = "";
                    deviceType = "";
                    // CS-F1-1WPFR
                    // CS-A1-1WPFR
                    // CS-C1-1FPFR
                    // resultString = "www.xxx.com\n456654855\nABCDEF\nCS-C3-21PPFR\n";
                    // 字符集合
                    String[] newlineCharacterSet = {
                            "\n\r", "\r\n", "\r", "\n"};
                    String stringOrigin = resultString;
                    // 寻找第一次出现的位置
                    int a = -1;
                    int firstLength = 1;
                    for (String string : newlineCharacterSet) {
                        if (a == -1) {
                            a = resultString.indexOf(string);
                            if (a > stringOrigin.length() - 3) {
                                a = -1;
                            }
                            if (a != -1) {
                                firstLength = string.length();
                            }
                        }
                    }

                    // 扣去第一次出现回车的字符串后，剩余的是第二行以及以后的
                    if (a != -1) {
                        resultString = resultString.substring(a + firstLength);
                    }
                    // 寻找最后一次出现的位置
                    int b = -1;
                    for (String string : newlineCharacterSet) {
                        if (b == -1) {
                            b = resultString.indexOf(string);
                            if (b != -1) {
                                mSerialNoStr = resultString.substring(0, b);
                                firstLength = string.length();
                            }
                        }
                    }

                    // 寻找遗失的验证码阶段
                    if (mSerialNoStr != null && b != -1 && (b + firstLength) <= resultString.length()) {
                        resultString = resultString.substring(b + firstLength);
                    }

                    // 再次寻找回车键最后一次出现的位置
                    int c = -1;
                    for (String string : newlineCharacterSet) {
                        if (c == -1) {
                            c = resultString.indexOf(string);
                            if (c != -1) {
                                mSerialVeryCodeStr = resultString.substring(0, c);
                            }
                        }
                    }

                    // 寻找CS-C2-21WPFR 判断是否支持wifi
                    if (mSerialNoStr != null && c != -1 && (c + firstLength) <= resultString.length()) {
                        resultString = resultString.substring(c + firstLength);
                    }
                    if (resultString != null && resultString.length() > 0) {
                        deviceType = resultString;
                    }

                    if (b == -1) {
                        mSerialNoStr = resultString;
                    }

                    if (mSerialNoStr == null) {
                        mSerialNoStr = stringOrigin;
                    }
                    // 判断是不是9位
                    isValidate();
                }
                // else {
                // 传感器添加 暂不实现
                // 网页/R1登录 暂不实现
                // 无法识别
                // handleLocalValidateSerialNoFail(ExtraException.SERIALNO_IS_ILLEGAL);
                // }
            }
        });


    }

    /**
     * 判断是不是合法
     *
     * @throws
     */
    private void isValidate() {
        mLocalValidate = new LocalValidate();
        try {
            mLocalValidate.localValidatSerialNo(mSerialNoStr);
        } catch (BaseException e) {
            handleLocalValidateSerialNoFail(e.getErrorCode());
            return;
        }

        if (!ConnectionDetector.isNetworkAvailable(mContext)) {
            ToastUtil.show(R.string.query_camera_fail_network_exception);
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putInt("type", 1);
        bundle.putString("SerialNo", mSerialNoStr);
        bundle.putString("very_code", mSerialVeryCodeStr);
        bundle.putString(EzWifiNetConfigActivity.DEVICE_TYPE, deviceType);
        Intent intent = new Intent(mContext, SearchEzDeviceActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void handleLocalValidateSerialNoFail(int errCode) {
        switch (errCode) {
            case ExtraException.SERIALNO_IS_NULL:
                ToastUtil.show(R.string.serial_number_is_null);
                break;
            case ExtraException.SERIALNO_IS_ILLEGAL:
                // showToast(R.string.serial_number_is_illegal);
                ToastUtil.show(R.string.unable_identify_two_dimensional_code_tip);
                break;
            default:
                ToastUtil.show(R.string.serial_number_error + "(" + errCode + ")");
                break;
        }
    }

    /**
     * 跳转添加探测器页面
     *
     * @see
     * @since V1.8.2
     */
    private boolean goAddProbe(String stringOrigin) {
        String[] newlineCharacterSet = {
                "\n\r", "\r\n", "\r", "\n"};

        String[] tempStr;
//        for (String sp : newlineCharacterSet) {
//
//            tempStr = stringOrigin.split(sp);
//            if (tempStr != null && tempStr.length == 5 && tempStr[4].length() == 4
//                    && DetectorType.isDetectorType(tempStr[4])) {
//                // 启动探测器关联界面
//                Intent intent = new Intent(CaptureActivity.this, AddProbeActivity.class);
//                intent.putExtra("probe_series", tempStr[1]);
//                intent.putExtra("probe_very_code", tempStr[2]);
//                intent.putExtra("probe_ex", tempStr[3]);
//                intent.putExtra("probe_type", tempStr[4]);
//                intent.putExtra("a1_device_series", mA1DeviceSeries);
//                startActivityForResult(intent, REQUEST_ADD_PROBE);
//                return true;
//            }
//        }
        return false;
    }

    @Override
    protected void initInject() {
        getFragmentComponent().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_monitor;
    }

    public void messageCount() {
        mPresenter.messageCount(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
    }

    @Override
    public void viewMessageCount(CommonBean messageCountBean) {

    }

    @Override
    public void showDeviceInfoList(List<EZDeviceInfo> deviceInfoList) {
        List<MultiItemEntity> entityList = new ArrayList<>();
        if (deviceInfoList != null) {
            for (EZDeviceInfo e :
                    deviceInfoList) {
                DeviceItemEntity entity = new DeviceItemEntity(e);
                entityList.add(entity);
            }
        }
        entityList.add(new AddItemEntity());
        mMonitorAdapter.setNewData(entityList);
    }
}
